import json
import xlwt
from entity.params import params

SUCCESS = True

class exportexcel:

    def __init__(self):
        global wb
        wb = xlwt.Workbook(encoding = "ascii")

    # 创建sheet
    def create_sheet(self, *args):
        worksheet = wb.add_sheet("casesresult")
        data = args[0]
        for index in range(len(data)):
            resultentity = data[index]
            xstyle = self.get_row_style(resultentity)
            # 构造单元格
            self.create_cell(worksheet, index, resultentity, xstyle)
        wb.save("./testcase/result.xls")

    # 获取行样式
    def get_row_style(self, args):
        xstyle = xlwt.easyxf('pattern: pattern solid, fore_colour light_green')
        # 获取参数对象信息
        resultentity = args
        # check 请求结果是否成功
        if self.check_result(resultentity) == False:
            # pattern.pattern_fore_colour = xlwt.Style.colour_map['red']
            xstyle = xlwt.easyxf('pattern: pattern solid, fore_colour red')
        # 自动换行
        xstyle.alignment.wrap = 1
        return xstyle

    def check_result(self, resultentity):
        resultcode = json.loads(str(resultentity.expectresult))['success']
        if resultcode == SUCCESS:
            return True
        return False

    # 创建单元格
    def create_cell(self, worksheet, index, param, xstyle):
        for cell in range(7):
            worksheet.col(cell).width = 256 * 20
            worksheet.write(index + 1, cell, str(self.get_cell_data(param, cell)), xstyle)




    def get_cell_data(self, p=params, cell=int):
        res = ""
        if cell == 0:
            res = p.caseno
        if cell == 1:
            res = p.casename
        if cell == 2:
            res = p.testname
        if cell == 3:
            res = p.apipath
        if cell == 4:
            res = p.params
        if cell == 5:
            res = p.expectresult
        if cell == 6:
            res = p.actualresult
        if cell == 7:
            res = p.requestmethod
        return res

